﻿using System;
using MangoCannon.Framework.Base;
using MangoCannon.Framework.Util;

namespace MangoCannon.Framework.Bussness
{
    public class MessageReader
    {
        public ClientMessage exchange(String msg)
        {
            ClientMessage msgInstance = new ClientMessage();
            MessageEntity msgEntity = new JsonHelper().DeserializeJsonToObject<MessageEntity>(msg);
            if (null != msgEntity.encrypt && !"".Equals(msgEntity.encrypt))
            {
                msgInstance.jsonText = decrypt(msgEntity.content,msgEntity.encrypt,msgEntity.key);
            }
            else
            {
                msgInstance.jsonText = msgEntity.content;
            }
            bool isOk = contentParse(msgEntity, msgInstance);
            if (!isOk)
            {
                Logger.getLogger().writeError(this,"Unknow message format received,Please check the server security!");
            }
            return msgInstance;
        }

        /// <summary>
        /// 内容转换
        /// </summary>
        /// <param name="entity">标准信息体</param>
        /// <param name="msg">消息体</param>
        /// <returns></returns>
        private bool contentParse(MessageEntity entity, ClientMessage msg)
        {
            bool flag = true;
            try
            {
                DanmuInfo dm= new JsonHelper().DeserializeJsonToObject<DanmuInfo>(entity.content);
                msg.ownerName = dm.nickname;
                msg.jsonText= entity.content;
                msg.giftName = dm.logtext;
                msg.isGift = dm.uid == "system" ? false : true;
                msg.giftQuantity = 1;
                msg.accessId = entity.accessId;
                //msg.receiveTime = DateTime.Parse((entity.rdate*10000+entity.rtime).ToString());
            }
            catch (Exception)
            {
            }
            return flag;
        }

        private string decrypt(string content,string encrypt,string key)
        {
            //预留解密入口，方便以后增加“加密解密业务”
            return "";
        }
    }
    public class MessageEntity
    {
        public int bid { get; set; }
        public string content { get; set; }
        public int rdate { get; set; }
        public int rtime { get; set; }
        public string accessId { get; set; }
        public int level { get; set; } //信息级别
        public string attr { get; set; }//信息属性
        public string encrypt { get; set; }//信息加密部分的内容
        public string key { get; set; } //信息钥匙
    }
    public class DanmuInfo
    {
        public string logtext { get; set; }
        public string uid { get; set; }
        public string bilibiliuid { get; set; }
        public string nickname { get; set; }
        public string datetime { get; set; }
        public string admin { get; set; }
        public string member { get; set; }
        public string vip { get; set; }
        public string roomid { get; set; }
        public string extra_info { get; set; }
    }
}
